<template>
  <div class="announcement-container">
    <div class="announcement-content">
      <p style="font-size: 20px;">{{ announcement || "暂无最新公告点击查看历史公告" }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElNotification } from 'element-plus';
import config from '../../public/config'

const announcement = ref(localStorage.getItem("announcement"));
let socket = null; // 用于存储 WebSocket 实例

onMounted(() => {
  if (!socket) { // 防止重复创建 WebSocket
    socket = new WebSocket(config.WS_URL);

    socket.onmessage = (event) => {
      announcement.value = event.data;
      localStorage.setItem("announcement", event.data);
      ElNotification({
        title: '公告',
        message: event.data,
        position: 'bottom-right'
      });
      // 使用 Electron 的 Notification API 显示系统通知
      if (window.Notification && Notification.permission === 'granted') {
        new Notification('公告', {
          body: event.data,
          // icon: 'path/to/icon.png' // 你可以指定一个图标路径
        });
      } else {
        // 如果没有通知权限，可以请求用户授权
        Notification.requestPermission().then(permission => {
          if (permission === 'granted') {
            new Notification('公告', {
              body: event.data,
              // icon: 'path/to/icon.png'
            });
          }
        });
      }

    };

    socket.onclose = () => {
      socket = null;
    };
  }
});

onUnmounted(() => {
  if (socket) {
    socket.close();
    socket = null;
  }
});
</script>


<style scoped>
.announcement-container {
  width: 80%;
  /* 容器宽度设置为 100% */
  overflow: hidden;
  /* 隐藏超出的部分 */
  cursor: pointer;
}

.announcement-content {
  display: inline-block;
  /* 横向排列内容 */
  white-space: nowrap;
  /* 防止文本换行 */
  animation: scroll 15s linear infinite;
  /* 设置动画效果 */
}

@keyframes scroll {
  0% {
    transform: translateX(100%);
    /* 从右侧开始 */
  }

  100% {
    transform: translateX(-100%);
    /* 滚动到左侧 */
  }
}
</style>